#include "Direct3DFramework.h"

int Direct3DFramework::drawBegin()
{
	//clear back-buffer and z-buffer
	if(FAILED(m_device->Clear(0,0,D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
		m_window->m_windowColor,1.0f,0)))
		return GPX_DRAW_CLEAR_ERROR;

	//begin drawing
	if(FAILED(m_device->BeginScene()))
		return GPX_DRAW_BEGIN_ERROR;

	return GPX_SUCCESS;
}

int Direct3DFramework::drawEnd()
{
	//end drawing
	if(FAILED(m_device->EndScene()))
		return GPX_DRAW_END_ERROR;

	//present the drawing
	if(FAILED(m_device->Present(0,0,0,0)))
		return GPX_DRAW_PRESENT_ERROR;

	return GPX_SUCCESS;
}

int Direct3DFramework::drawText(char* a_text, V2DF a_pos, int a_color)
{
	//create direct3d color with given packed color
	D3DCOLOR color = D3DCOLOR(a_color);

	//create text rect
	RECT rect = {0,0,0,0};
	m_font->DrawText(0,TEXT(a_text),-1,&rect,DT_CALCRECT,color);

	//translate position
	rect.left   += (long)a_pos.x;
	rect.top    += (long)a_pos.y;
	rect.right  += (long)a_pos.x;
	rect.bottom += (long)a_pos.y;

	//draw text
	m_font->DrawText(0,TEXT(a_text),-1,&rect,0,color);

	return GPX_SUCCESS;
}

int Direct3DFramework::drawTexture(BeanieTexture* a_texture)
{
	if(a_texture->m_culling)
		return GPX_SUCCESS;

	//grab correct texture
	D3DFTexture* texture = m_textureList[a_texture->m_texId];

	//create center point and rect
	D3DXVECTOR3 center(a_texture->m_texCen.x,a_texture->m_texCen.y,0.0f);

	RECT rect;
	rect.top    = (long)a_texture->m_texMin.y;
	rect.left   = (long)a_texture->m_texMin.x;
	rect.bottom = (long)a_texture->m_texMax.y;
	rect.right  = (long)a_texture->m_texMax.x;

	//set transformation
	m_sprite->SetTransform(&texture->m_matrices[a_texture->m_matId].m_world);

	//begin drawing
	if(FAILED(m_sprite->Begin(D3DXSPRITE_ALPHABLEND)))
		return GPX_DRAW_BEGIN_TEXTURE_ERROR;

	//draw texture
	if(FAILED(m_sprite->Draw(texture->m_texture,
		&rect,&center,0,0xffffffff)))
		return GPX_DRAW_TEXTURE_ERROR;

	//end drawing
	if(FAILED(m_sprite->End()))
		return GPX_DRAW_END_TEXTURE_ERROR;

	return GPX_SUCCESS;
}

int Direct3DFramework::drawLine(V2DF a_start, V2DF a_end, int m_color)
{
	D3DXVECTOR2 line[2] =
	{
		D3DXVECTOR2(a_start.x+m_camPos.x,a_start.y+m_camPos.y),
		D3DXVECTOR2(a_end.x  +m_camPos.x,  a_end.y+m_camPos.y)
	};

	m_line->SetAntialias(true);
	m_line->SetWidth(2.5f);

	m_line->Begin();
	m_line->Draw(line,2,m_color);
	m_line->End();

	return GPX_SUCCESS;
}